import {LoginAPI} from "@/request/login"

interface State {
    isLogin: boolean;
    token: string;
    isAdmin: string;
}
const store = {
    // 存放数据
    state: {
        isLogin: false,
        token: '001',
        isAdmin: '9999'
    },
    // 放同步方法
    actions: {
        SET_ISLOGIN(newState: {isLogin: boolean}, action: {tag: boolean}) {
            newState.isLogin = action.tag
        },

        SET_TOKEN(newState: State, action: {token: string}) {
            // console.log("actions exe", action)
            newState.token = action.token
        },
        SET_ADMIN(newState: State, action: {isAdmin: string}) {
            newState.isAdmin = action.isAdmin
        },
    },

    asyncActions: {
        login(loginParam: LoginAPIReq) {
            return async (dispatch: any, getState: () => State) => {
                try {
                    const res = await LoginAPI(loginParam);
                    if (res.code === 200) {
                        dispatch({ type: 'SET_ISLOGIN', tag: true });
                        dispatch({ type: 'SET_TOKEN', token: res.data.token });
                        dispatch({ type: 'SET_ADMIN', isAdmin: 'asdfasdf' });
                        localStorage.setItem('TOKEN', res.data.token)
                        // 在所有 dispatch 之后返回 Promise
                        return {
                            code: res.code,
                            state: getState()
                        }
                    }
                } catch (err) {
                    console.log(err);
                }
            };
        },
    },

    actionNames:{}
}
const actionNames = {}
for(const key in store.actions){
    actionNames[key]=key
}
store.actionNames=actionNames
export default store